package cn.java.servlet;

import cn.java.bean.User;
import cn.java.mapper.UserMapper;

import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
    @Autowired
    private UserMapper userMapper;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        userMapper = (UserMapper)context.getBean("userMapper");


        //利用request对象获取URL请求传来的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("username", username);
        paramMap.put("password", password);
        List<User> user = userMapper.selectByMap(paramMap);

        // 查找到了说明登录成功
        if (user.size() >= 1) {
            request.getRequestDispatcher("/pages/success.jsp").forward(request, response);
        } else {
            // 密码或者账号不正确
            response.sendRedirect("/pages/fail.jsp");
        }


    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

